<?php
/**
 * account.php
 *
 * Account management
 *
 * @author     Makai Lajos
 * @copyright  2015
 * @license    License.txt
 * @version    2.0
 * @link       http://opencart-api.com/product/opencart-restful-api-pro-v2-0/
 * @see        http://newapi2.opencart-api.com/demo/
 */
require_once(DIR_SYSTEM . 'engine/restcontroller.php');

class ControllerRestAccount extends RestController {

	private $error = array();
//获取个人资料
	public function getAccount() {
    
    $this->load->model('account/customer');

		$json = array('success' => true);

		$this->language->load('account/edit');


		if (!$this->customer->isLogged()) {
			$json["error"]["warning"] = "用户还没有登陆";
			$json["success"] = false;
		}
		
		if($json["success"]){
		
			$this->load->model('account/customer');
			
			$user = $this->model_account_customer->getCustomer($this->customer->getId());
            /*
            $manageTelList = array(
                //18616897011,//陈启令
                //13761945128,//计哲
                //13025007000,//鲍远义
                //13916629872,//陈海明
                13661895330,//孙建华
                //13816354916,//刘颖川
            );
            if (in_array($user['telephone'], $manageTelList)) {
                //$user['telephone'] = 15189732366;//模拟业务员调试（刘颂颂（金华））
                $user['telephone'] = 13382214258;//模拟业务员调试（陈保宋）
            }
            // */
            $user = array_merge($user, $this->model_account_customer->userCheckByTelephone($user['telephone']));
            $user['MG_saleGatherInfo'] = $this->model_account_customer->getSaleGatherInfo($user);

			// Custom Fields
			$this->load->model('account/custom_field');

			$user['custom_fields'] = $this->model_account_custom_field->getCustomFields($this->config->get('config_customer_group_id'));

      if(strpos(VERSION, '2.1.') === false){
          $user['account_custom_field'] = unserialize($user['custom_field']);
      } else {
          $user['account_custom_field'] = json_decode($user['custom_field'], true);
      }
      //修改license_image和avatar
      // $base_url = $this->config->get('config_url');
      // $this->load->model('tool/upload');
      // $img_keys = array('license_image');
      // foreach ($img_keys as $img_key) {
      //   $img = $this->model_tool_upload->getUploadByCode($user[$img_key]);
      //   if($img) {
      //     $img_url = $base_url . 'system/storage/upload/' . $img['filename'];
      //     $user[$img_key] = $img_url;  
      //   }
      // }

      //Liqn 获取用户名下之图片
      $customer_images = $this->model_account_customer->getCustomerImages($this->customer->getId());
      $base_url = $this->config->get('config_url');
      foreach ($customer_images as $key => $ci) {
        $img_url = $base_url . 'system/storage/upload/' . $ci['filename'];
        $customer_images[$key]['img_url'] = $img_url;
      }
      $license_images = array();
      $shop_images = array();
      foreach ($customer_images as $key => $ci) {
        if($ci['type']==1){
          $shop_images[] = $ci;
        }
        if($ci['type']==2){
          $license_images[] = $ci;
        }
      }
      $user['shop_images'] = $shop_images;
      $user['license_images'] = $license_images;
      //Liqn 添加商超类型
      $user['shop_type_content'] = getShopTypes()[$user['shop_type']];

      //Liqn 添加会员积分
      $points = $this->customer->getRewardPoints();
      $user['points'] = empty($points)?0:$points;

      //Liqn 添加总下单金额
      $order_amount = $this->customer->getTotalOrderAmount();
      $user['order_amount'] = empty($order_amount)?0:$order_amount;

      

			unset($user["password"]);
			unset($user["salt"]);
			unset($user['custom_field']);			
			$json["data"] = $user;
		}

		if ($this->debugIt) {
			echo '<pre>';
			print_r($json);
			echo '</pre>';
		} else {
			$this->response->setOutput(json_encode($json));
		}
	}

	public function saveAccount($post) {

		$json = array('success' => true);
		
		if (!$this->customer->isLogged()) {
			$json["error"]['warning']= "用户还没有登陆";
			$json["success"] = false;
		}else {
			if ($this->validate($post)) {
				$this->load->model('account/customer');
				$this->model_account_customer->neweditCustomer($post);

        //Liqn 保存地推信息
        if(isset($post['recommended_code'])) {
          $result = $this->model_account_customer->getGroundIdByCode($post['recommended_code']);
          $customer_id = $this->customer->getId();
          $ground_id = 0;
          if($result) {
            $ground_id = $result['ground_id'];
          }
          $this->model_account_customer->saveRecommendedCode($customer_id, $post['recommended_code'], $ground_id); 
        }
			}else {
				$json["error"]['warning'] = $this->error;
				$json["success"] = false;
			}
		}

		if ($this->debugIt) {
			echo '<pre>';
			print_r($json);
			echo '</pre>';
		} else {
			$this->response->setOutput(json_encode($json));
		}					
	}
//验证修改信息
	protected function validate($post) {
		
		$this->load->model('account/customer');
		$this->language->load('account/edit');	

    if(isset($post['fullname'])){
      if ((utf8_strlen($post['fullname']) < 2) || (utf8_strlen($post['fullname']) > 32)) {
        $this->error['fullname'] = $this->language->get('error_fullname');
      }
    }else{
      $this->error['fullname'] = $this->language->get('error_fullname');
    }

    if(isset($post['company_name'])){
      if ((utf8_strlen($post['company_name']) < 2) || (utf8_strlen($post['company_name']) > 32)) {
        $this->error['company_name'] = $this->language->get('error_company_name');
      }
    }else{
      $this->error['company_name'] = $this->language->get('error_company_name');
    }

    $code = $post['shop_code'];
    if(empty($code)) {
      //$this->error["upload"] = "上传图片不能为空";
    } else if(count($code)>10) {
      //$this->error["upload"] = "最多上传十张照片";
    } 
    else {
      $this->load->model('tool/upload');
      foreach ($code as $cd) {
        $upload_info = $this->model_tool_upload->getUploadByCode($cd);
        if(empty($upload_info)) {
          //$this->error["upload"] = "上传店铺实景图片不存在";
          //break;   
        }
      }
    }

    $code = array();
    $code = $post['license_code'];
    if(empty($code)) {
      $this->error["upload"] = "上传图片不能为空";
    } else if(count($code)>1) {
      $this->error["upload"] = "最多上传一张照片";
    } 
    else {
      $this->load->model('tool/upload');
      foreach ($code as $cd) {
        $upload_info = $this->model_tool_upload->getUploadByCode($cd);
        if(empty($upload_info)) {
          $this->error["upload"] = "上传营业执照图片不存在";
          break;   
        }
      }
    }
	
		// Custom field validation
		$this->load->model('account/custom_field');

		$custom_fields = $this->model_account_custom_field->getCustomFields($this->config->get('config_customer_group_id'));

		foreach ($custom_fields as $custom_field) {
			if (($custom_field['location'] == 'account') && $custom_field['required'] && empty($post['custom_field'][$custom_field['custom_field_id']])) {
				$this->error['custom_field'][$custom_field['custom_field_id']] = sprintf($this->language->get('error_custom_field'), $custom_field['name']);
			}
		}
		if (!$this->error) {
			return true;
		} else {
			return false;
		}
	}

	/*
	* ACCOUNT FUNCTIONS
	*/	
	public function account() {

		$this->checkPlugin();
		
		if ( $_SERVER['REQUEST_METHOD'] === 'GET' ){
			//get account details

			$this->getAccount();			
		}else if ( $_SERVER['REQUEST_METHOD'] === 'POST' ){
			//modify account
			$requestjson = file_get_contents('php://input');
		
			$requestjson = json_decode($requestjson, true);           

			if (!empty($requestjson)) {       
				$this->saveAccount($requestjson);
			}else {
				$this->response->setOutput(json_encode(array('success' => false)));
			}   

		}
  }

	public function password() {

		$this->checkPlugin();
		
		 if ( $_SERVER['REQUEST_METHOD'] === 'PUT' ){
			//modify account password
			$requestjson = file_get_contents('php://input');
		
			$requestjson = json_decode($requestjson, true);           

			if (!empty($requestjson)) {       
				$this->changePassword($requestjson);
			}else {
				$this->response->setOutput(json_encode(array('success' => false)));
			}   

		}

    }

	public function changePassword($post) {

		$json = array('success' => true);
		
		if (!$this->customer->isLogged()) {
			$json["error"]['warning'] = "用户还未登录";
			$json["success"] = false;
		}else {
			if ((utf8_strlen($post['password']) < 6) || (utf8_strlen($post['password']) > 32)) {
				$json["error"]['password'] = "输入的号码小于6位或者大于32位";
			}

			//二次验证密码
			if (isset($data['confirm'])&&$data['confirm'] != $data['password'])  {
				$json['error']['warning'] = $this->language->get('error_confirm');
			}
        

			if (empty($json["error"])) {
				$this->load->model('account/customer');

				$this->model_account_customer->editPassword($this->customer->getEmail(), $post['password']);

				// Add to activity log
				$this->load->model('account/activity');

				$activity_data = array(
					'customer_id' => $this->customer->getId(),
					'name'        => $post['fullname']
				);

				$this->model_account_activity->addActivity('password', $activity_data);			
			}else {
				$json["success"] = false;
			}
		}

		if ($this->debugIt) {
			echo '<pre>';
			print_r($json);
			echo '</pre>';
		} else {
			$this->response->setOutput(json_encode($json));
		}					
	}



	public function customfield() {
		$this->checkPlugin();

		if ( $_SERVER['REQUEST_METHOD'] === 'GET' ){
			
		$this->load->model('account/custom_field');

		// Customer Group
		if (isset($this->request->get['customer_group_id']) && is_array($this->config->get('config_customer_group_display')) && in_array($this->request->get['customer_group_id'], $this->config->get('config_customer_group_display'))) {
			$customer_group_id = $this->request->get['customer_group_id'];
		} else {
			$customer_group_id = $this->config->get('config_customer_group_id');
		}


		$json['custom_fields'] = $this->model_account_custom_field->getCustomFields($customer_group_id);

		/*$custom_fields = $this->model_account_custom_field->getCustomFields($customer_group_id);

		foreach ($custom_fields as $custom_field) {
			$json[] = array(
				'custom_field_id' => $custom_field['custom_field_id'],
				'required'        => $custom_field['required']
			);
		}*/

	}else {
		$json["error"]["warning"]= "Only GET request method allowed";
		$json["success"]	= false;

	}    
		if ($this->debugIt) {
			echo '<pre>';
			print_r($json);
			echo '</pre>';
		} else {
			$this->response->setOutput(json_encode($json));
		}
	}

    private function editAddress($id, $data) {
        $this->load->model('account/address');

        $json = $this->validateAdress($data);

        if($json['success']){
            $this->model_account_address->editAddress($id, $data);
        }

        $this->response->setOutput(json_encode($json));
    }

    private function addAddress($data) {

        $json = $this->validateAdress($data);
        $this->load->model('account/address');

        $this->load->model('account/customer');
        if($json['success']){
            $id = $this->model_account_address->addAddress($data);
            $customer = $this->model_account_customer->getCustomer($this->customer->getId());
            $logcenter_id = $customer['logcenter_id'];
            if(empty($logcenter_id) || $logcenter_id == 0 ){
              $logcenter_id = $this->model_account_address->closeZone($data);
            }
            
            if($id){
                $json['address_id'] = $id;
            } else {
                $json['success'] = false;
            }
        }

        $this->response->setOutput(json_encode($json));
    }


    private function deleteAddress($id) {

        $json = array('success' => true);

        $this->load->model('account/address');
        $this->model_account_address->deleteAddress($id);
        $this->response->setOutput(json_encode($json));
    }

    private function getAddress($id) {

        $json = array('success' => true);

        $this->load->model('account/address');

        $address = $this->model_account_address->getAddress($id);
        if(!empty($address)) {
            // Custom Fields
            $this->load->model('account/custom_field');

            $address['custom_fields'] = $this->model_account_custom_field->getCustomFields($this->config->get('config_customer_group_id'));
            $json["data"] = $address;
        } else {
            $json['success'] = false;
        }

        $this->response->setOutput(json_encode($json));
    }

    private function listAddress() {

        $json = array('success' => true);

        $this->load->model('account/address');

        $data['addresses'] = $this->model_account_address->getAddresses();

        // Custom Fields
        $this->load->model('account/custom_field');

        $data['custom_fields'] = $this->model_account_custom_field->getCustomFields($this->config->get('config_customer_group_id'));

        if(count($data['addresses']) > 0){
            $json["data"] = $data;
        }else {
            $json["success"]	= false;
            $json["error"]["warning"] = "你还没有添加收货地址";
        }

        $this->response->setOutput(json_encode($json));
    }

    public function validateAdress($post) {

        $json = array('success'=>true);

        if (!$post['fullname']) {
            $json['error']['warning'] = "收货人姓名不得为空";
            $json['success'] = false;
        }

        if (!preg_match('/^1[0-9]{10}$/', $post['shipping_telephone'])) {
				$json['error']['warning'] ="收货人号码填写有误";
				$json['success'] = false;
			}

		/*if (!$post['company']) {
            $json['error']['warning'] = "收货公司名称不得为空";
            $json['success'] = false;
        }*/


        $this->load->model('localisation/country');      
        $country_info = $this->model_localisation_country->getCountry($post['country_id']);

        $this->load->model('localisation/zone');
        $zone_info = $this->model_localisation_zone->getZone($post['zone_id']);

        $this->load->model('localisation/city');
        $city_info = $this->model_localisation_city->getCity($post['city_id']);


        if ((utf8_strlen(trim($post['address'])) < 3) || (utf8_strlen(trim($post['address'])) > 128)) {
            $json['error']['warning'] = "详细地址太短小或者太长";
            $json['success'] = false;
        }


        if ($post['country_id'] == '' || !is_numeric($post['country_id'])) {
            $json['error']['warning'] = "找不到省或市";
            $json['success'] = false;
        }

        if (!isset($post['zone_id']) || $post['zone_id'] == '' || !is_numeric($post['zone_id'])) {
            $json['error']['warning'] = "找不到市或区";
            $json['success'] = false;
        }

         if (!isset($post['city_id']) || $post['city_id'] == '' || !is_numeric($post['city_id'])) {
            $json['error']['warning'] = "找不到信息";
            $json['success'] = false;
        }

        return $json;
    }

    /*
    * ADDRESS FUNCTIONS
    */
    public function address() {

        $this->checkPlugin();

        if (!$this->customer->isLogged()) {
            $this->response->setOutput(json_encode(array('success' => false, "error"=>array("warning"=>"用户没有登陆"))));
        } else {
            if ( $_SERVER['REQUEST_METHOD'] === 'GET' ){
                if (isset($this->request->get['id']) && ctype_digit($this->request->get['id'])) {
                    $this->getAddress($this->request->get['id']);
                }else {
                    $this->listAddress();
                }
            } else if ( $_SERVER['REQUEST_METHOD'] === 'POST' ){
                $requestjson = file_get_contents('php://input');
                $requestjson = json_decode($requestjson, true);

                if (!empty($requestjson)) {
                    $this->addAddress($requestjson);
                } else {
                    $this->response->setOutput(json_encode(array('success' => false)));
                }
            } else if ( $_SERVER['REQUEST_METHOD'] === 'PUT' ){
                $requestjson = file_get_contents('php://input');
                $requestjson = json_decode($requestjson, true);

                if (isset($this->request->get['id']) && ctype_digit($this->request->get['id'])
                    && !empty($requestjson)) {
                    $this->editAddress($this->request->get['id'], $requestjson);
                } else {
                    $this->response->setOutput(json_encode(array('success' => false)));
                }
            } else if ( $_SERVER['REQUEST_METHOD'] === 'DELETE' ){
                if (isset($this->request->get['id']) && ctype_digit($this->request->get['id'])){
                    $this->deleteAddress($this->request->get['id']);
                }
            }
        }
    }

    public function saveLicenseImage() {
      // $this->checkPlugin();
      $json = array('success'=>false);
      if (!$this->customer->isLogged()) {
        $json["error"]["warning"] = "用户还没有登陆";
        $this->response->setOutput(json_encode($json));
        return;
      }
      
      // $media_id = $this->request->post['media_id'];
      $requestjson = file_get_contents('php://input');
      $requestjson = json_decode($requestjson, true);   
      $media_id = $requestjson['media_id'];

      $opt = array(
            'appsecret'=>WxPayConfig::APPSECRET,
            'appid'=>WxPayConfig::APPID,
            'cachedir'=>DIR_CACHE
      );
      $jssdk = new EasyWechat($opt);
      $file_content = $jssdk->getMedia($media_id);
      if(!$file_content){
        $json["error"]["warning"] = $jssdk->errMsg;
        $this->response->setOutput(json_encode($json));
        return;
      }

      $file_name = $media_id . '.jpg';
      $file_path = DIR_UPLOAD . $file_name;

      file_put_contents($file_path, $file_content);

      //保存到统一的upload数据表
      $this->load->model('tool/upload');
      $code = $this->model_tool_upload->addUpload($file_name, $file_name);
      //保存code到customer表
      $this->load->model('account/customer');
      $this->model_account_customer->saveLicenseImage($this->customer->getId(), $code);
      //返回img url给前端
      $base_url = $this->config->get('config_url');
      $img_url = $base_url . 'system/storage/upload/' . $file_name;
      $this->response->setOutput(json_encode(array('img_url'=>$img_url, 'success'=>true)));
  }

  public function saveCustomerImages() {
      // $this->checkPlugin();
      $json = array('success'=>false);
      if (!$this->customer->isLogged()) {
        $json["error"]["warning"] = "用户还没有登陆";
        $this->response->setOutput(json_encode($json));
        return;
      }
      
      // $media_id = $this->request->post['media_id'];
      $requestjson = file_get_contents('php://input');
      $requestjson = json_decode($requestjson, true);   
      $code = $requestjson['code'];
      if(empty($code)) {
        $json["error"]["warning"] = "上传图片不能为空";
      }

      $this->load->model('tool/upload');
      foreach ($code as $cd) {
        $upload_info = $this->model_tool_upload->getUploadByCode($cd);
        if(empty($upload_info)) {
          $json["error"]["warning"] = "部分上传图片不存在";
          break;   
        }
      }

      //保存code到customer表
      // $this->load->model('account/customer');
      // $this->model_account_customer->saveLicenseImage($this->customer->getId(), $code);
      
      $this->response->setOutput(json_encode(array('message'=>'修改上传图片成功', 'success'=>true)));
  }

  public function saveIs_invoice() {

    $this->load->language('account/order');

    $json = array();
    if ( $_SERVER['REQUEST_METHOD'] === 'POST' ){
      
      $requestjson = file_get_contents('php://input');
    
      $requestjson = json_decode($requestjson, true);

      $post    = $requestjson;
      
    
      if (isset($this->request->get['order_id'])) {
        $order_id = $this->request->get['order_id'];

      } else {
        $order_id = 0;
      }
      if($order_id){
        $json['order_id']=$order_id;
      }
      

      $json['success'] = false;
    
      if($order_id){
        $this->load->model('account/order');

        $order_info = $this->model_account_order->getOrder($order_id);
        if($order_info['customer_id']){
          $json['customer_id']=$order_info['customer_id'];
        }
        
        if ($order_info && $order_info['customer_id'] && isset($post['is_invoice_id'])) {
          if($order_info['bill_status'] == 0 || $order_info['bill_status'] == 1 ){
            switch ($post['is_invoice_id']) {
              case '0':

                $this->model_account_order->saveIs_invoice($order_id,'0');
                $json['success_info'] = $this->language->get('text_is_invoice_removed');
                $json['success'] = true;
                $json['is_billed'] = '0';
                break;
              case '1':
                $this->model_account_order->saveIs_invoice($order_id,'1');
                $json['success_info'] = $this->language->get('text_is_invoice_added');
                $json['success'] = true;
                $json['is_billed'] = '1';
                break;
              default:
                break;
            }    
          }else{
            $json['error']['warning']='您的发票已开出,无法修改';
          }
                
        }else{
          $json['error']['warning']='修改失败';
        }     
      }   
    $this->response->addHeader('Content-Type: application/json');
    $this->response->setOutput(json_encode($json));
   }
  }
  
  public function coupon() {

    $this->checkPlugin();
    
    if ( $_SERVER['REQUEST_METHOD'] === 'GET' ){
      //get account details

      $this->getCoupons();      
    }
  }

  public function getCoupons() {
    $json = array('success' => true);

    $this->load->model('account/customer');
    $avaiable_coupons = $this->model_account_customer->getCustomerCoupons($this->customer->getId());
    $json['data'] = $avaiable_coupons;
    if ($this->debugIt) {
      echo '<pre>';
      print_r($json);
      echo '</pre>';
    } else {
      $this->response->setOutput(json_encode($json));
    }
  }


//用户订阅新闻
/*	public function newsletter() {

		$this->checkPlugin();

		if ( $_SERVER['REQUEST_METHOD'] === 'PUT' ){
			if (isset($this->request->get['subscribe']) && ctype_digit($this->request->get['subscribe'])){
				$this->subscribe($this->request->get['subscribe']);
			} else {
				$this->sendResponse(array('success' => false));
			}
		}
	}

	public function subscribe($subscribe) {

		$json = array('success' => true);

		if (!$this->customer->isLogged()) {
			$json["error"] = "User is not logged in";
			$json["success"] = false;
		}else {
			$this->load->model('account/customer');
			$this->model_account_customer->editNewsletter($subscribe);
		}

		$this->sendResponse($json);
	}
*/	
    /*
     * 精简版‘业务管理’验证，用于footer
     * @author sonicsjh
     */
    public function managerCheck() {
        $json["managerCheck"] = false;
        if ($this->customer->isLogged()) {
            $this->load->model('account/customer');
            $user = $this->model_account_customer->getCustomer($this->customer->getId());
            $json['managerCheck'] = (bool)array_sum($this->model_account_customer->userCheckByTelephone($user['telephone']));
            //$json["saleCheck"] = $this->model_account_customer->userCheckByTelephone($user['telephone']);
        }
        $this->response->setOutput(json_encode($json));
    }

}